package cn.iocoder.yudao.module.resource.api;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.infra.service.file.UploadFileResult;
import cn.iocoder.yudao.module.resource.api.model.StoryDTO;
import cn.iocoder.yudao.module.resource.controller.admin.story.vo.StoryPageReqVO;
import cn.iocoder.yudao.module.resource.dal.dataobject.story.StoryDO;
import cn.iocoder.yudao.module.resource.service.story.StoryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StoryApiImpl implements IStoryApi {
    @Resource
    private StoryService storyService;

    @Resource
    private FileService fileService;

    @Override
    public PageResult<StoryDTO> getStoryPage(Integer roleId, PageParam pageParam) {
        final StoryPageReqVO pageReqVO = new StoryPageReqVO();
        pageReqVO.setRoleId(roleId);
        pageReqVO.setPageNo(pageParam.getPageNo());
        pageReqVO.setPageSize(pageParam.getPageSize());
        PageResult<StoryDO> pageResult = storyService.getStoryPage(pageReqVO);

        PageResult<StoryDTO> dtoPageResult = BeanUtils.toBean(pageResult, StoryDTO.class);

        final List<Long> fileIdList = dtoPageResult.getList().stream().map(v -> v.getFileId()).collect(Collectors.toList());
        final List<UploadFileResult> fileResults = fileService.getFile(fileIdList, null);

        Map<Long, UploadFileResult> fileResultMap = fileResults.stream()
                .collect(Collectors.toMap(UploadFileResult::getFileId, c -> c));
        for (StoryDTO dto : dtoPageResult.getList()) {
            UploadFileResult uploadFileResult = fileResultMap.get(dto.getFileId());
            if (uploadFileResult != null) {
                dto.setFileUrl(uploadFileResult.getFileUrl());
            }
        }

        return dtoPageResult;
    }

    @Override
    public StoryDTO getStory(Integer id) {
        final StoryDO story = storyService.getStory(id);
        final StoryDTO bean = BeanUtils.toBean(story, StoryDTO.class);
        if (bean != null){
            final UploadFileResult file = fileService.getFile(bean.getFileId(), null);
            bean.setFileUrl(file.getFileUrl());
        }
        return bean;
    }

}
